<template>
  <div class="product-detail">
    <el-row>
      <el-col :span="8">
        <div class="product-image">
          <img :src="product.imageUrl" alt="商品图片" />
        </div>
      </el-col>
      <el-col :span="16">
        <div class="product-info">
          <h1 class="product-name">{{ product.name }}</h1>
          <div class="product-price">¥{{ (product.price || 0).toFixed(2) }}</div>
          <div class="product-desc">{{ product.description }}</div>
          <div class="product-stock">库存: {{ product.stock }}</div>
          <div class="product-category">分类: {{ product.category?.name || '未分类' }}</div>
          <div class="product-created">创建时间: {{ formatDate(product.createdAt) }}</div>
          
          <div class="purchase-options">
            <div class="quantity-selector">
              <el-input-number
                v-model="quantity"
                :min="1"
                :max="product.stock > 0 ? product.stock : 999"
                label="购买数量"
                :disabled="product.stock <= 0"
              />
            </div>
            
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="large"
                @click="addToCart"
                :disabled="product.stock <= 0"
              >
                加入购物车
              </el-button>
              <el-button 
                type="warning" 
                size="large"
                @click="buyNow"
                :disabled="product.stock <= 0"
              >
                立即购买
              </el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 商品详情内容 -->
    <div class="product-content">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="商品详情" name="details">
          <div class="details-content" v-html="product.detailContent || '暂无详情'">
          </div>
        </el-tab-pane>
        <el-tab-pane label="用户评价" name="reviews">
          <div class="reviews-content">
            <div v-if="reviews.length === 0" class="no-reviews">暂无评价</div>
            <div v-else>
              <div v-for="review in reviews" :key="review.id" class="review-item">
                <div class="review-user">{{ review.userName }}</div>
                <div class="review-rating">
                  <el-rate :value="review.rating" disabled show-score></el-rate>
                </div>
                <div class="review-content">{{ review.content }}</div>
                <div class="review-time">{{ formatDate(review.createdAt) }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 相关推荐 -->
    <div class="related-products">
      <h3>相关推荐</h3>
      <div class="related-list">
        <el-card 
          v-for="item in relatedProducts" 
          :key="item.id" 
          class="related-card"
          @click="handleRelatedProductClick(item.id)"
        >
          <img :src="item.imageUrl" alt="商品图片" class="related-image">
          <div class="related-title">{{ item.name }}</div>
          <div class="related-price">¥{{ (item.price || 0).toFixed(2) }}</div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { productService } from '../services/productService'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCartStore } from '../store'
import { useUserStore } from '../store'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 商品ID
const productId = computed(() => route.params.id)

// 商品数据
const product = ref({
  id: '',
  name: '',
  price: 0,
  description: '',
  stock: 0,
  imageUrl: '',
  category: null,
  createdAt: ''
})

// 购买数量
const quantity = ref(1)

// 激活的标签页
const activeTab = ref('details')

// 评价数据
const reviews = ref([])

// 相关商品数据
const relatedProducts = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 加载商品详情
const loadProductDetail = async () => {
  try {
    console.log('加载商品详情，ID:', productId.value)
    
    // 检查productId是否有效
    if (!productId.value) {
      console.error('商品ID无效')
      ElMessage.error('商品ID无效')
      return
    }
    
    const result = await productService.getProductDetail(productId.value)
    console.log('商品详情结果:', result)
    
    // 处理不同的数据结构
    let productData = {}
    if (result && result.data) {
      productData = result.data
    } else if (result && result.id) {
      productData = result
    }
    
    // 确保所有必需字段都有默认值
    product.value = {
      id: productData.id || '',
      name: productData.name || '未知商品',
      price: Number(productData.price) || 0,
      description: productData.description || '暂无描述',
      stock: Number(productData.stock) || 0,
      imageUrl: productData.imageUrl || '/placeholder.png',
      category: productData.category || null,
      createdAt: productData.createdAt || new Date().toISOString(),
      detailContent: productData.detailContent || '暂无详情'
    }
    
    // 设置购买数量的最大值
    if (product.value.stock > 0) {
      quantity.value = 1
    } else {
      quantity.value = 0
    }
    
    console.log('处理后的商品数据:', product.value)
  } catch (error) {
    console.error('加载商品详情失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      ElMessage.error('加载商品详情失败')
    }
    
    // 设置默认商品数据，防止渲染错误
    product.value = {
      id: '',
      name: '商品加载失败',
      price: 0,
      description: '无法加载商品信息',
      stock: 0,
      imageUrl: '/placeholder.png',
      category: null,
      createdAt: new Date().toISOString(),
      detailContent: '无法加载商品详情'
    }
    quantity.value = 0
  }
}

// 加载相关商品
const loadRelatedProducts = async () => {
  try {
    console.log('加载相关商品')
    const result = await productService.getProducts(1, 4)
    console.log('相关商品结果:', result)
    
    // 处理不同的数据结构
    let products = []
    
    if (result && result.data) {
      products = result.data
    } else if (Array.isArray(result)) {
      products = result
    }
    
    // 确保每个商品都有默认值，防止渲染错误
    relatedProducts.value = products.map(product => ({
      id: product.id || '',
      name: product.name || '未知商品',
      price: Number(product.price) || 0,
      description: product.description || '暂无描述',
      stock: Number(product.stock) || 0,
      imageUrl: product.imageUrl || '/placeholder.png',
      category: product.category || null
    }))
    
    console.log('处理后的相关商品数据:', relatedProducts.value)
  } catch (error) {
    console.error('加载相关商品失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    }
    
    // 设置空数组，防止渲染错误
    relatedProducts.value = []
  }
}

// 添加到购物车
const addToCart = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    // 不自动跳转到登录页，而是让用户决定
    ElMessageBox.confirm('请先登录后再添加购物车', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/login')
    }).catch(() => {
      // 用户选择不登录，不做任何操作
    })
    return
  }
  
  try {
    console.log('添加到购物车，商品ID:', product.value.id, '数量:', quantity.value)
    await cartStore.addToCart(product.value, quantity.value)
    ElMessage.success('添加购物车成功')
  } catch (error) {
    console.error('添加购物车失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      ElMessage.error('添加购物车失败')
    }
  }
}

// 立即购买
const buyNow = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    // 不自动跳转到登录页，而是让用户决定
    ElMessageBox.confirm('请先登录后再购买商品', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/login')
    }).catch(() => {
      // 用户选择不登录，不做任何操作
    })
    return
  }
  
  // 检查商品库存
  if (product.value.stock <= 0) {
    ElMessage.error('商品库存不足')
    return
  }
  
  // 检查购买数量
  if (quantity.value <= 0) {
    ElMessage.warning('请选择购买数量')
    return
  }
  
  console.log('立即购买，商品信息:', {
    id: product.value.id,
    name: product.value.name,
    price: product.value.price,
    quantity: quantity.value,
    stock: product.value.stock
  })
  
  // 将完整的商品信息存入localStorage，然后跳转到订单确认页面
  localStorage.setItem('buyNowProduct', JSON.stringify({
    productId: product.value.id,
    productName: product.value.name,
    productPrice: product.value.price,
    productImage: product.value.imageUrl || '/product.jpg',
    quantity: quantity.value,
    stock: product.value.stock
  }))
  
  // 清空购物车缓存，确保立即购买的纯净性
  localStorage.removeItem('checkoutCart')
  
  router.push('/order/confirm')
}

// 处理相关商品点击
const handleRelatedProductClick = (id) => {
  router.push(`/product/${id}`)
}

// 页面加载时初始化数据
onMounted(() => {
  console.log('商品详情页加载，商品ID:', productId.value)
  loadProductDetail()
  loadRelatedProducts()
})

// 监听路由参数变化
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('路由参数变化，从', oldId, '到', newId)
    loadProductDetail()
    loadRelatedProducts()
  }
}, { immediate: true })
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.product-image {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 20px;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.product-info {
  padding-left: 40px;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.product-price {
  font-size: 28px;
  color: #ff4d4f;
  margin-bottom: 20px;
}

.product-desc,
.product-stock,
.product-category,
.product-created {
  font-size: 16px;
  margin-bottom: 15px;
  color: #666;
}

.purchase-options {
  margin-top: 40px;
}

.quantity-selector {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.product-content {
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #f0f0f0;
}

.details-content {
  padding: 20px;
  font-size: 16px;
  line-height: 1.8;
}

.reviews-content {
  padding: 20px;
}

.no-reviews {
  text-align: center;
  color: #999;
  padding: 40px;
}

.review-item {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.review-user {
  font-weight: bold;
  margin-bottom: 10px;
}

.review-rating {
  margin-bottom: 10px;
}

.review-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.review-time {
  color: #999;
  font-size: 14px;
}

.related-products {
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #f0f0f0;
}

.related-products h3 {
  font-size: 20px;
  margin-bottom: 20px;
}

.related-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.related-card {
  height: 250px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.related-image {
  width: 100%;
  height: 150px;
  object-fit: contain;
}

.related-title {
  font-size: 14px;
  margin: 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-price {
  font-size: 16px;
  color: #ff4d4f;
}
</style>